﻿using Microsoft.AspNetCore.Http;
using System.Threading.Tasks;

namespace WebZHX.Middleware
{
    /// <summary>
    /// OPTIONS 请求处理中间件
    /// </summary>
    public class OptionsMiddleware
    {
        private readonly RequestDelegate _next;

        public OptionsMiddleware(RequestDelegate next)
        {
            _next = next;
        }

        public async Task InvokeAsync(HttpContext context)
        {
            if (context.Request.Method == "OPTIONS")
            {
                context.Response.StatusCode = 200;
                context.Response.Headers.Add("Access-Control-Allow-Origin", "http://10.50.98.42:8010");
                //context.Response.Headers.Add("Access-Control-Allow-Origin", "http://localhost:3000");
                context.Response.Headers.Add("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, OPTIONS");
                context.Response.Headers.Add("Access-Control-Allow-Headers", "Content-Type, Authorization, X-Requested-With");
                context.Response.Headers.Add("Access-Control-Allow-Credentials", "true");
                context.Response.Headers.Add("Access-Control-Max-Age", "86400");

                await context.Response.WriteAsync("OK");
                return;
            }

            await _next(context);
        }
    }
}
